﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace wz.common
{
    /// <summary>
    /// 百度签名算法
    /// </summary>
    public static class BaiduAlgorithm 
    {
        public static bool Validate(NameValueCollection nvCol, string key,string inputSign)
        {
            Dictionary<string, string> dic = nvCol.Keys.Cast<string>().Where(item => item != "sign").ToDictionary(item => item, item => nvCol[item]);

            var sortdic = dic.OrderBy(c => c.Key);

            var s = new StringBuilder();
            foreach (var d in sortdic)
            {
                s.Append(d.Key + "=" + d.Value);
            }
            s.Append(key);
            string sign = FormsAuthentication.HashPasswordForStoringInConfigFile(s.ToString(), "MD5");
            return sign == inputSign;
        }


        /// <summary>
        /// 生成Sign字段
        /// </summary>
        /// <param name="key"></param>
        /// <param name="nvCol"></param>
        /// <returns></returns>
        public static string GeneSign(string key, NameValueCollection nvCol)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (string item in nvCol.Keys)
            {
                dic.Add(item, HttpUtility.UrlDecode(nvCol[item]));
            }

            var sortdic = dic.OrderBy(c => c.Key);

            var s = new StringBuilder();
            foreach (var d in sortdic)
            {
                s.Append(d.Key + "=" + d.Value);
            }
            string sign = FormsAuthentication.HashPasswordForStoringInConfigFile(s + key, "MD5");
            return sign;
        }
    }
}